package com.xinqi.modules.sys.role.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.role.convert.UserRoleConvert;
import com.xinqi.modules.sys.role.domain.UserRoleEntity;
import com.xinqi.modules.sys.role.dto.req.AddUserRoleDTO;
import com.xinqi.modules.sys.role.dto.req.UserRoleCreateDTO;
import com.xinqi.modules.sys.role.dto.req.UserRoleDeleteDTO;
import com.xinqi.modules.sys.role.dto.req.UserRoleQueryDTO;
import com.xinqi.modules.sys.role.dto.req.UserRoleUpdateDTO;
import com.xinqi.modules.sys.role.dto.rsp.UserRoleResultDTO;
import com.xinqi.modules.sys.role.manager.UserRoleManager;
import com.xinqi.modules.sys.role.service.UserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 系统用户角色服务层实现
 *
 * @author: linkai
 * @date: 2023/04/01
 */
@Validated
@Service("userRoleService")
@RequiredArgsConstructor
public class UserRoleServiceImpl implements UserRoleService {
    private final UserRoleConvert userRoleConvert;
    private final UserRoleManager userRoleManager;

    /**
     * 分页查询 系统用户角色数据
     */
    @Override
    @DS("slaver")
    public PageInfo<UserRoleResultDTO> page(Param pageable, UserRoleQueryDTO query) {
        IPage<UserRoleEntity> page = userRoleManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, userRoleConvert::convert);
    }

    /**
     * 查询 系统用户角色数据
     */
    @Override
    public List<UserRoleResultDTO> find(UserRoleQueryDTO query) {
        return userRoleManager.list(wrapper(query)).stream()
            .map(userRoleConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<UserRoleEntity> wrapper(UserRoleQueryDTO query) {
        LambdaQueryWrapper<UserRoleEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(UserRoleEntity::getId, v));
        return wrapper;
    }

    /**
     * 根据id查询 系统用户角色数据
     */
    @Override
    public UserRoleResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(userRoleManager.findById(id)).map(userRoleConvert::convert).orElse(null);
    }

    /**
     * 新增 系统用户角色数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid UserRoleCreateDTO dto) {
        UserRoleEntity entity = userRoleConvert.create(dto);
        userRoleManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 系统用户角色数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid UserRoleUpdateDTO dto) {
        Optional.ofNullable(userRoleManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        UserRoleEntity entity = userRoleConvert.update(dto);
        return userRoleManager.updateById(entity);
    }

    /**
     * 根据id删除 系统用户角色数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return userRoleManager.removeById(id);
    }

    /**
     * 根据id删除 系统用户角色数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(UserRoleDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUserRole(AddUserRoleDTO dto) {
        LambdaQueryWrapper<UserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        // 删除
        userRoleManager.remove(queryWrapper.eq(UserRoleEntity::getUserId, dto.getUserId()));
        // 批量添加
        List<UserRoleEntity> list = dto.getRoleIdList().stream().map(v -> {
            UserRoleEntity entity = new UserRoleEntity();
            entity.setUserId(dto.getUserId());
            entity.setRoleId(v);
            return entity;
        }).collect(Collectors.toList());
        userRoleManager.saveBatch(list);
    }

}
